package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.IdWorker;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    //查询所有用户信息
    @Override
    public Page<User> findAll(Map<String, Object> searchMap) {
        Integer currentPage = Integer.parseInt(searchMap.get("currentPage").toString());
        Integer pageSize = Integer.parseInt(searchMap.get("pageSize").toString());
        PageHelper.startPage(currentPage, pageSize);
        Example example = this.createExample(searchMap);
        Page<User> userPage = (Page<User>) userMapper.selectByExample(example);
        return userPage;
    }

    //重置用户密码
    @Override
    @Transactional
    public void resetPassword(Map<String, Object> userVO) {
        String uid = userVO.get("uid").toString();
        String passWord = userVO.get("passWord").toString();
        //md5工具类加密
        String encode = MD5Utils.md5(passWord);
        userMapper.resetPassWord(uid, encode);
    }

    //编辑用户
    @Override
    @Transactional
    public void edit(Map<String, Object> userVO) {
        //将map转为user对象
        String userStr = JSON.toJSONString(userVO);
        User user = JSON.parseObject(userStr, User.class);
        //取出密码 进行加密
        String passWord = user.getPassWord();
        passWord = MD5Utils.md5(passWord);
        user.setUpdateTime(new Date());
        //将加密的密码赋值
        user.setPassWord(passWord);
        //修改操作
        userMapper.updateByPrimaryKey(user);
    }

    //删除用户
    @Override
    @Transactional
    public void delete(Map<String, Object> userVO) {
        String uid = userVO.get("uid").toString();
        userMapper.deleteByPrimaryKey(uid);
    }

    @Override
    public User findByUserName(String userName) {
        Example example=new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userName",userName);
        List<User> users = userMapper.selectByExample(example);
        return users.get(0);
    }

    //修改密码
    @Override
    @Transactional
    public Integer updatePwd(String uid, String oldPwd, String newPwd) {
        User user = userMapper.selectByPrimaryKey(uid);
        if (oldPwd != null && MD5Utils.md5(oldPwd).equals(user.getPassWord())) {
            user.setPassWord(MD5Utils.md5(newPwd));
            userMapper.updateByPrimaryKey(user);
            return 1;
        }
        return 0;
    }

    //用户编辑信息
    @Override
    @Transactional
    public void editUser(Map<String, Object> userVO) {
        //将map转为user对象
        String userStr = JSON.toJSONString(userVO);
        User user = JSON.parseObject(userStr, User.class);
        user.setUpdateTime(new Date());
        //修改操作
        userMapper.updateByPrimaryKey(user);
    }

    @Autowired
    private IdWorker idWorker;
    @Override
    public boolean save(Map userVO) {
        User user = new User();
        user.setAvatar((String)userVO.get("avatar"));
        user.setBirthday((Date) userVO.get("birthday"));
        user.setCommentStatus((Integer) userVO.get("commentStatus"));
        user.setEmail((String)userVO.get("email"));
        String gender = (String) userVO.get("gender");
        if ("男".equals(gender) || "1".equals(gender)) {
            user.setGender(1);
        }else {
            user.setGender(2);
        }
        user.setMobile((String) userVO.get("mobile"));
        user.setNickName((String) userVO.get("nickName"));
        user.setOccupation((String) userVO.get("occupation"));
        String password = (String) userVO.get("occupation");
        user.setOccupation(MD5Utils.md5(password));
        user.setQqNumber((String) userVO.get("qqNumber"));
        user.setSource((String) userVO.get("source"));
        user.setStartEmailNotification((Integer) userVO.get("qqNumber"));
        user.setStatus((Integer)userVO.get("status"));
        user.setSummary((String) userVO.get("summary"));
        user.setUid(String.valueOf(idWorker.nextId()));
        user.setUserName((String) userVO.get("userName"));
        user.setUuid((String) userVO.get("uuid"));
        user.setWeChat((String) userVO.get("weChat"));
        user.setUserTag((Integer)userVO.get("userTag"));
        user.setLoginCount(0L);
        user.setCommentStatus(1);
        user.setIpSource((String) userVO.get("ipSource"));
        user.setBrowser((String) userVO.get("browser"));
        user.setOs((String) userVO.get("os"));
        userMapper.insert(user);
        return true;
    }



    @Override
    public void update(User user) {
        userMapper.updateByPrimaryKey(user);
    }

    //获取用户信息
    @Override
    public User findById(String uid) {
        return userMapper.selectByPrimaryKey(uid);
    }

    /**
     * 构建查询对象
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 唯一uid
            if (searchMap.get("uid") != null && !"".equals(searchMap.get("uid"))) {
                criteria.andLike("uid", "%" + searchMap.get("uid") + "%");
            }
            // 用户名
            if (searchMap.get("userName") != null && !"".equals(searchMap.get("userName"))) {
                criteria.andLike("userName", "%" + searchMap.get("userName") + "%");
            }
            // 密码
            if (searchMap.get("passWord") != null && !"".equals(searchMap.get("passWord"))) {
                criteria.andLike("passWord", "%" + searchMap.get("passWord") + "%");
            }

            // 性别(1:男2:女)
            if (searchMap.get("gender") != null) {
                criteria.andEqualTo("gender", searchMap.get("gender"));
            }

            // 个人头像
            if (searchMap.get("avatar") != null && !"".equals(searchMap.get("avatar"))) {
                criteria.andEqualTo("avatar", searchMap.get("avatar"));
            }

            // 邮箱
            if (searchMap.get("email") != null && !"".equals(searchMap.get("email"))) {
                criteria.andEqualTo("email", searchMap.get("email"));
            }
            // 出生年月日
            if (searchMap.get("birthday") != null) {
                criteria.andEqualTo("birthday", searchMap.get("birthday"));
            }

            // 手机
            if (searchMap.get("mobile") != null && !"".equals(searchMap.get("mobile"))) {
                criteria.andEqualTo("mobile", searchMap.get("mobile"));
            }

            // 邮箱验证码
            if (searchMap.get("validCode") != null && !"".equals(searchMap.get("validCode"))) {
                criteria.andEqualTo("validCode", searchMap.get("validCode"));
            }

            // 自我简介最多150字
            if (searchMap.get("summary") != null && !"".equals(searchMap.get("summary"))) {
                criteria.andEqualTo("summary", searchMap.get("summary"));
            }

            // 登录次数
            if (searchMap.get("loginCount") != null) {
                criteria.andEqualTo("loginCount", searchMap.get("loginCount"));
            }

            // 最后登录时间
            if (searchMap.get("lastLoginTime") != null) {
                criteria.andEqualTo("lastLoginTime", searchMap.get("lastLoginTime"));
            }

            // 最后登录IP
            if (searchMap.get("lastLoginIp") != null && !"".equals(searchMap.get("lastLoginIp"))) {
                criteria.andEqualTo("lastLoginIp", searchMap.get("lastLoginIp"));
            }

            // 状态
            if (searchMap.get("status") != null) {
                criteria.andEqualTo("status", searchMap.get("status"));
            }

            // 创建时间
            if (searchMap.get("createTime") != null) {
                criteria.andEqualTo("createTime", searchMap.get("createTime"));
            }

            // 更新时间
            if (searchMap.get("updateTime") != null) {
                criteria.andEqualTo("updateTime", searchMap.get("updateTime"));
            }

            // 昵称
            if (searchMap.get("nickName") != null && !"".equals(searchMap.get("nickName"))) {
                criteria.andEqualTo("nickName", searchMap.get("nickName"));
            }

            // 资料来源
            if (searchMap.get("source") != null && !"".equals(searchMap.get("source"))) {
                criteria.andEqualTo("source", searchMap.get("source"));
            }

            // 平台uuid
            if (searchMap.get("uuid") != null && !"".equals(searchMap.get("uuid"))) {
                criteria.andEqualTo("uuid", searchMap.get("uuid"));
            }

            // QQ号
            if (searchMap.get("qqNumber") != null && !"".equals(searchMap.get("qqNumber"))) {
                criteria.andEqualTo("qqNumber", searchMap.get("qqNumber"));
            }

            // 微信号
            if (searchMap.get("weChat") != null && !"".equals(searchMap.get("weChat"))) {
                criteria.andEqualTo("weChat", searchMap.get("weChat"));
            }

            // 职业
            if (searchMap.get("occupation") != null && !"".equals(searchMap.get("occupation"))) {
                criteria.andEqualTo("occupation", searchMap.get("occupation"));
            }

            // 评论状态 1:正常 0:禁言
            if (searchMap.get("commentStatus") != null) {
                criteria.andEqualTo("commentStatus", searchMap.get("commentStatus"));
            }

            // ip来源
            if (searchMap.get("ipSource") != null && !"".equals(searchMap.get("ipSource"))) {
                criteria.andEqualTo("ipSource", searchMap.get("ipSource"));
            }

            // 浏览器
            if (searchMap.get("browser") != null && !"".equals(searchMap.get("browser"))) {
                criteria.andEqualTo("browser", searchMap.get("browser"));
            }

            // 操作系统
            if (searchMap.get("os") != null && !"".equals(searchMap.get("os"))) {
                criteria.andEqualTo("os", searchMap.get("os"));
            }

            // 是否开启邮件通知 1:开启 0:关闭
            if (searchMap.get("startEmailNotification") != null) {
                criteria.andEqualTo("startEmailNotification", searchMap.get("startEmailNotification"));
            }

            // 用户标签：0：普通用户，1：管理员，2：博主 等
            if (searchMap.get("userTag") != null) {
                criteria.andEqualTo("userTag", searchMap.get("userTag"));
            }

        }
        return example;
    }
}
